import { h } from './component/element';
import Sheet from './component/sheet';
import { cssPrefix } from './config';
import DataProxy from './core/data_proxy';
import './index.less';
import { locale } from './locale/locale';

export default class VuiSheet {
  constructor(options = {}) {
    this.container = document.createElement('div');
    this.options = options;

    this.data = this.createDataProxy();
    const rootEl = h('div', cssPrefix).on('contextmenu', evt => evt.preventDefault());
    // create canvas element
    this.container.appendChild(rootEl.el);
    this.sheet = new Sheet(rootEl, this.data);
  }

  /**
   * 创建数据代理
   * @param {*}
   * @return {*}
   */
  createDataProxy() {
    const d = new DataProxy('sheet1', this.options);
    d.change = (...args) => {
      this.sheet.trigger('change', ...args);
    };
    return d;
  }

  /**
   * 加载数据
   * @param {*} data
   * @return {*}
   */
  loadData(data) {
    this.data = this.createDataProxy();
    this.data.setData(data);
    this.sheet.resetData(this.data);
    return this;
  }

  /**
   * 获取数据
   * @param {*}
   * @return {*}
   */
  getData() {
    return this.data.getData();
  }

  cellText(ri, ci, text) {
    this.data.setCellText(ri, ci, text, 'finished');
    return this;
  }

  cell(ri, ci) {
    return this.data.getCell(ri, ci);
  }

  cellStyle(ri, ci) {
    return this.data.getCellStyle(ri, ci);
  }

  reRender() {
    this.sheet.table.render();
    return this;
  }

  on(eventName, func) {
    this.sheet.on(eventName, func);
    return this;
  }

  validate() {
    const { validations } = this.data;
    return validations.errors.size <= 0;
  }

  change(cb) {
    this.sheet.on('change', data => {
      cb(this.getData());
    });
    return this;
  }

  static locale(lang, message) {
    locale(lang, message);
  }

  appendTo(parent) {
    if (parent instanceof HTMLElement) {
      parent.appendChild(this.container);
    }
  }
}
